package data.dao.daoImplementation;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import data.dao.*;
import data.dto.*;
import data.searchdto.*;

public class LeaveDAOImpl implements LeaveDAO {

	@Override
	public ArrayList<LeaveDTO> findLeave(LeaveSearchDTO leaveSearchdto)
			throws LeaveDAOException, SQLException {
		ArrayList<LeaveDTO> list;
		PreparedStatement stmt = null;

		try {
			list = searchMatching(util.Database.getInstance().getConnection(),
					leaveSearchdto);

		} finally {
			if (stmt != null)
				stmt.close();
		}
		return list;
	}

	@Override
	public ArrayList<LeaveDTO> findAllLeave() throws LeaveDAOException,
			SQLException {

		String sql = "SELECT * FROM leave ORDER BY id ASC ";
		ArrayList<LeaveDTO> searchResults = listQuery(util.Database
				.getInstance().getConnection().prepareStatement(sql));

		return searchResults;
	}

	@Override
	public void insertLeaveDetail(LeaveDTO LeaveDetail)
			throws LeaveDAOException, SQLException {

		String sql = "";
		PreparedStatement stmt = null;

		try {
			sql = "INSERT INTO leave ( id, leavetype, startedate, "
					+ "enddate, natureofleave, reason, "
					+ "workdissemination, contactdetails, createdby, "
					+ "createdon, modifiedby, modifiedon, "
					+ "status, 1) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
			stmt = util.Database.getInstance().getConnection()
					.prepareStatement(sql);

			stmt.setInt(1, LeaveDetail.getId());
			stmt.setInt(2, LeaveDetail.getLeaveType());
			stmt.setInt(3, LeaveDetail.getStartDate());
			stmt.setInt(4, LeaveDetail.getEndDate());
			stmt.setInt(5, LeaveDetail.getNatureOfLeave());
			stmt.setString(6, LeaveDetail.getReason());
			stmt.setString(7, LeaveDetail.getWorkDisemmination());
			stmt.setString(8, LeaveDetail.getContactDetails());
			stmt.setInt(9, util.CurrentUser.getInstance().getUserId());
			stmt.setTimestamp(10, util.CurrentDate.getCurrentTimeStamp());
			stmt.setInt(11, util.CurrentUser.getInstance().getUserId());
			stmt.setTimestamp(12, util.CurrentDate.getCurrentTimeStamp());
			stmt.setInt(13, LeaveDetail.getStatus());

			int rowcount = stmt.executeUpdate();
			if (rowcount != 1) {
				// System.out.println("PrimaryKey Error when updating DB!");
				throw new SQLException("PrimaryKey Error when updating DB!");
			}

		} finally {
			if (stmt != null)
				stmt.close();
		}

	}

	@Override
	public void updateLeaveDetail(LeaveDTO LeaveDetail)
			throws LeaveDAOException, SQLException, NotFoundException {

		String sql = "UPDATE leave SET leavetype = ?, startedate = ?, enddate = ?, "
				+ "natureofleave = ?, reason = ?, workdissemination = ?, "
				+ "contactdetails = ?, "
				+ "modifiedby = ?, modifiedon = ?, status = ?  WHERE id = ? ";
		PreparedStatement stmt = null;

		try {
			stmt = util.Database.getInstance().getConnection()
					.prepareStatement(sql);
			stmt.setInt(1, LeaveDetail.getLeaveType());
			stmt.setInt(2, LeaveDetail.getStartDate());
			stmt.setInt(3, LeaveDetail.getEndDate());
			stmt.setInt(4, LeaveDetail.getNatureOfLeave());
			stmt.setString(5, LeaveDetail.getReason());
			stmt.setString(6, LeaveDetail.getWorkDisemmination());
			stmt.setString(7, LeaveDetail.getContactDetails());
			stmt.setInt(8, LeaveDetail.getModifiedBy());
			stmt.setTimestamp(9, util.CurrentDate.getCurrentTimeStamp());
			stmt.setInt(10, LeaveDetail.getStatus());

			stmt.setInt(11, LeaveDetail.getId());

			int rowcount = stmt.executeUpdate();
			if (rowcount == 0) {
				// System.out.println("Object could not be saved! (PrimaryKey not found)");
				throw new NotFoundException(
						"Object could not be saved! (PrimaryKey not found)");
			}
			if (rowcount > 1) {
				// System.out.println("PrimaryKey Error when updating DB! (Many objects were affected!)");
				throw new SQLException(
						"PrimaryKey Error when updating DB! (Many objects were affected!)");
			}
		} finally {
			if (stmt != null)
				stmt.close();
		}

	}

	@Override
	public void deleteLeaveDetail(LeaveDTO LeaveDetail)
			throws LeaveDAOException, SQLException, NotFoundException {

		String sql = "DELETE FROM leave WHERE (id = ? ) ";
		PreparedStatement stmt = null;

		try {

			stmt = util.Database.getInstance().getConnection()
					.prepareStatement(sql);
			stmt.setInt(1, LeaveDetail.getId());

			int rowcount = stmt.executeUpdate();
			if (rowcount == 0) {
				// System.out.println("Object could not be deleted (PrimaryKey not found)");
				throw new NotFoundException(
						"Object could not be deleted! (PrimaryKey not found)");
			}
			if (rowcount > 1) {
				// System.out.println("PrimaryKey Error when updating DB! (Many objects were deleted!)");
				throw new SQLException(
						"PrimaryKey Error when updating DB! (Many objects were deleted!)");
			}
		} finally {
			if (stmt != null)
				stmt.close();
		}

	}

	public ArrayList<LeaveDTO> searchMatching(Connection conn,
			LeaveSearchDTO valueObject) throws SQLException {

		ArrayList<LeaveDTO> searchResults;

		boolean first = true;
		StringBuffer sql = new StringBuffer("SELECT * FROM leave WHERE 1=1 ");

		if (valueObject.getLeaveType() != 0) {
			if (first) {
				first = false;
			}
			sql.append("AND leavetype = ").append(valueObject.getLeaveType())
					.append(" ");
		}

		if (valueObject.getStartDate() != 0) {
			if (first) {
				first = false;
			}
			sql.append("AND startedate = ").append(valueObject.getStartDate())
					.append(" ");
		}

		if (valueObject.getEndDate() != 0) {
			if (first) {
				first = false;
			}
			sql.append("AND enddate = ").append(valueObject.getEndDate())
					.append(" ");
		}

		sql.append("ORDER BY id ASC ");

		// Prevent accidential full table results.
		// Use loadAll if all rows must be returned.
		if (first)
			searchResults = new ArrayList<LeaveDTO>();
		else
			searchResults = listQuery(conn.prepareStatement(sql.toString()));

		return searchResults;
	}

	protected ArrayList<LeaveDTO> listQuery(PreparedStatement stmt)
			throws SQLException {

		ArrayList<LeaveDTO> searchResults = new ArrayList<LeaveDTO>();
		ResultSet result = null;
		LeaveDTO temp;

		try {
			result = stmt.executeQuery();

			while (result.next()) {
				temp = new LeaveDTO();

				temp.setId(result.getInt("id"));
				temp.setLeaveType(result.getShort("leavetype"));
				temp.setStartDate(result.getInt("startedate"));
				temp.setEndDate(result.getInt("enddate"));
				temp.setNatureOfLeave(result.getShort("natureofleave"));
				temp.setReason(result.getString("reason"));
				temp.setWorkDisemmination(result.getString("workdissemination"));
				temp.setContactDetails(result.getString("contactdetails"));
				temp.setCreatedBy(result.getInt("createdby"));
				temp.setCreatedOn(result.getTimestamp("createdon"));
				temp.setModifiedBy(result.getInt("modifiedby"));
				temp.setModifiedOn(result.getTimestamp("modifiedon"));
				temp.setStatus(result.getShort("status"));

				searchResults.add(temp);
			}

		} finally {
			if (result != null)
				result.close();
			if (stmt != null)
				stmt.close();
		}

		return searchResults;
	}

}
